<template>
    <div class="container" ref="container">
        <div class="container_layer" @mousemove="mouseMove" @mouseup="mouseUp">
            <div class="container_layer_box" ref="moveBox"
                :style="{ '--left': moveDetail.left + 'px', '--top': moveDetail.top + 'px' }" @mousedown="mouseDown"
                >{{ moveDetail }}</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
let isDown = ref(false);
let downDetail = ref({
    clientX: 0,
    clientY: 0
});
let moveDetail = ref({
    top: 0,
    left: 0
})
let container = ref();
let moveBox = ref();
const mouseDown = (event: MouseEvent) => {
    isDown.value = true;
    downDetail.value = {
        clientX: event.clientX-moveBox.value.offsetLeft,
        clientY: event.clientY-moveBox.value.offsetTop
    }
    return event.preventDefault();
}
const mouseMove = (event: MouseEvent) => {
    if (!isDown.value) return;
    let { clientX, clientY } = event;
    let containerRects = container.value.getClientRects();
    if (!(containerRects && containerRects.length)) return;
    let containerRect = containerRects[0];
    let ofl = clientX - downDetail.value.clientX;
    let oft = clientY - downDetail.value.clientY;

    if (ofl < 0) {
        ofl = 0;
    }
    if (ofl > containerRect.width - moveBox.value.clientWidth) {
        ofl = containerRect.width - moveBox.value.clientWidth
    }
    if (oft < 0) {
        oft = 0;
    }
    if (oft > containerRect.height - moveBox.value.clientHeight) {
        oft = containerRect.height - moveBox.value.clientHeight
    }
    moveDetail.value.left = ofl;
    moveDetail.value.top = oft;
    return event.preventDefault();
}
const mouseUp = (event:MouseEvent) => {
    isDown.value = false;
    return event.preventDefault();
}
</script>

<style scoped>
.container {
    position: absolute;
    left: 300px;
    top: 300px;
    width: 600px;
    height: 300px;
    box-shadow: 0px 0px 5px skyblue;
}

.container_layer {
    width: 100%;
    height: 100%;
    position: relative;
}

.container_layer_box {
    position: absolute;
    left: var(--left);
    top: var(--top);
    width: 60px;
    height: 60px;
    background-color: skyblue;
}
</style>